package com.yazi.mxz.admin.controller;

import java.util.List;

import javax.annotation.Resource;

import com.myframework.smhj.hibernate.Paging;
import com.myframework.smhj.hibernate.Searching;
import com.myframework.smhj.hibernate.Page;
import com.myframework.smhj.jackson.result.ObjectResult;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yazi.mxz.common.controller.BaseController;
import com.yazi.mxz.common.entity.beans.Member;
import com.yazi.mxz.common.entity.beans.MemberNotice;
import com.yazi.mxz.common.entity.beans.MemberNoticeId;
import com.yazi.mxz.common.service.MemberNoticeService;
import com.yazi.mxz.common.service.MemberService;

@Controller("memberNoticeController")
@RequestMapping("/memberNotice")
public class MemberNoticeController extends BaseController {
	private static Logger log = LoggerFactory.getLogger(MemberNoticeController.class);
	
	@Resource
	MemberNoticeService memberNoticeService;
	@Resource
	MemberService memberService;
	
	@RequestMapping("/addDo/json")
	@ResponseBody
	public ObjectResult<?> addDoJson(Long[] memberIds, Long noticeId, Searching si){
		log.debug("给用户绑定通知：noticeId={}", noticeId);
		ObjectResult<Paging> jsonResult = new ObjectResult<Paging>();
		try{
			Paging pi = si;
			if (null != memberIds && memberIds.length > 0) {// 发给指定(一个或多个)用户
				for (Long memberId : memberIds) {
					MemberNoticeId id = new MemberNoticeId();
					id.setMemberId(memberId);
					id.setNoticeId(noticeId);
					MemberNotice mn = new MemberNotice();
					mn.setId(id);
					memberNoticeService.add(mn);
				}
				
			} else {// 发给所有用户
				
				Page<Member> page = memberService.list(null, si);
				List<Member> list = page.getList();
				pi = page.getPaging();
				for (Member member: list) {
					MemberNoticeId id = new MemberNoticeId();
					id.setMemberId(member.getMemberId());
					id.setNoticeId(noticeId);
					MemberNotice mn = new MemberNotice();
					mn.setId(id);
					memberNoticeService.add(mn);
				}
			}
			jsonResult.setResult(pi);
			jsonResult.setOkMessage("添加成功!");
		} catch (Exception e){
			log.error("给用户绑定通知异常：", e);
			jsonResult.setErrorMessage("添加失败!");
		}
		return jsonResult;
	}
	
}
